#include "pd_log.h"
#include "pd_tcp_ioc.h"
#include "pd_transport.h"

void pd_tcpfd_on_readable(PdIOComponent *ioc)
{
    if (NULL == ioc)
    {
        PD_LOG(WARN, "ioc null pointer");
    }
    else if (NULL == ioc->sock)
    {
        PD_LOG(WARN, "sock null pointer");
    }
    else
    {
        const uint32_t BUFFER_SIZE = 4096;
        char buffer[BUFFER_SIZE];
        if (0 == read(pd_socket_get_fd(ioc->sock), buffer, BUFFER_SIZE))
        {
            PD_LOG(INFO, "client close tcp, peer=[%s]", pd_socket_str_peer(ioc->sock));
            pd_tcpfd_on_error(ioc);
        }
        else
        {
            PD_LOG(INFO, "read from peer=[%s], [%s]", pd_socket_str_peer(ioc->sock), buffer);
        }
    }
}

void pd_tcpfd_on_writeable(PdIOComponent *ioc)
{
    UNUSED(ioc);
}

void pd_tcpfd_on_error(PdIOComponent *ioc)
{
    if (NULL == ioc)
    {
        PD_LOG(WARN, "ioc null pointer");
    }
    else if (NULL == ioc->sock)
    {
        PD_LOG(WARN, "sock null pointer");
    }
    else if (NULL == ioc->ts)
    {
        PD_LOG(WARN, "ts null pointer");
    }
    else if (0 != pd_transport_remove_ioc(ioc->ts, ioc))
    {
        PD_LOG(WARN, "pd_transport_remove_ioc fail, ioc=%p", ioc);
    }
    else
    {
        PD_LOG(INFO, "tcp fd error, will close, ioc=%p sock=%p", ioc, ioc->sock);
        pd_socket_destroy(ioc->sock);
        pd_ioc_free(ioc);
    }
}

